<template>
  <div class="panel left-middle">
    <div class="rose-chart" ref="chartRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

// 模拟数据
const generateData = () => {
  return [
    { value: 35, name: '水稻' },
    { value: 25, name: '小麦' },
    { value: 20, name: '玉米' },
    { value: 15, name: '大豆' },
    { value: 5, name: '其他' }
  ]
}

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  
  const option = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(51, 255, 208, 0.3)',
      borderWidth: 1,
      padding: [8, 12],
      textStyle: {
        color: '#fff'
      },
      formatter: '{b}: {c}%'
    },
    legend: {
      orient: 'vertical',
      right: '5%',
      top: 'center',
      textStyle: {
        color: '#fff',
        fontSize: 10
      },
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 10
    },
    series: [
      {
        name: '农作物分布',
        type: 'pie',
        radius: ['30%', '90%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 0,
          borderColor: 'rgba(0, 0, 0, 0.3)',
          borderWidth: 1
        },
        label: {
          show: false
        },
        emphasis: {
          scale: true,
          scaleSize: 5,
          label: {
            show: true,
            fontSize: 12,
            color: '#33ffd0',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: generateData(),
        roseType: 'radius',
        animationType: 'scale',
        animationEasing: 'elasticOut',
        animationDelay: function (idx: number) {
          return Math.random() * 200
        }
      }
    ],
    color: [
      '#33ffd0',
      '#2ed573',
      '#ffa502',
      '#ff4757',
      '#9333ea'
    ]
  }
  
  chart.setOption(option)
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
  window.removeEventListener('resize', handleResize)
})

const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.rose-chart {
  height: 100%;
  width: 100%;
}
</style>
